//
//  ASRDebugLog.m
//  testASR
//
//  Created by YangShuai on 16/9/22.
//  Copyright © 2016年 WanKang. All rights reserved.
//

#import "ASRDebugLog.h"
static BOOL isShowLog = YES;

static NSString *logPath  = nil;
NSMutableArray *logArray = nil;
NSFileHandle *inFile = nil;

@implementation ASRDebugLog
+ (void) showLog:(NSString *)format, ...
{
    if ( isShowLog) {
        va_list args;
        va_start(args, format);
        NSString *str = [[NSString alloc] initWithFormat:format arguments:args];
        va_end(args);
        NSLog(@"[ASRTEK] %@",str);
        //[str release];
    }
}


+ (void) setShowLog:(BOOL)showLog
{
    isShowLog = showLog;
}
/*
 * @将系统时间和打印的日志组合，然后写入数组中
 */
+ (void) addString:(NSString *)str
{
    NSString *nowDate = [NSDate date];
    NSString *log = [NSString stringWithFormat:@"%@---%@\n",nowDate,str];
    [logArray addObject:log];
    
}

+ (void) createFile
{
    NSArray *appArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([appArray count] > 0) {
        NSString *docPath = [appArray objectAtIndex:0];
        logPath = [docPath stringByAppendingPathComponent:@"msc_ios.log"];
        // 判断文件是否存在
        NSFileManager *fileManager =  [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:logPath]) {
            [fileManager createFileAtPath:logPath contents:nil attributes:nil];
        }
        
        inFile = [NSFileHandle fileHandleForWritingAtPath:logPath];
    }
}

/*
 * @将log写入文件
 */
+ (void) writeLog
{
    if (logPath == nil) {
        [ASRDebugLog createFile];
    }
    
    // 定位到文件末尾
    [inFile seekToEndOfFile];
    
    for (int i = 0; i < [logArray count]; i++) {
        NSString *log = [logArray objectAtIndex: i];
        [inFile writeData: [log dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [inFile closeFile];
    
    [logArray removeAllObjects];
}


@end
